/**
 * 
 */
package cn.chinasyq.photoquan.photo.adapter;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

public class PhotoPagerTabAdapter extends FragmentPagerAdapter {

	private static final String TAG = PhotoPagerTabAdapter.class.getName();

	private final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();

	private Context mContext = null;
	private ViewPager mViewPager = null;
	private FragmentManager mFManager = null;
	private Fragment mCurrentPrimaryItem = null;

	public PhotoPagerTabAdapter(FragmentActivity activity, ViewPager viewPager) {
		super(activity.getSupportFragmentManager());
		this.mFManager = activity.getSupportFragmentManager();
		this.mContext = activity;
		viewPager.setAdapter(this);
		this.mViewPager = viewPager;
	}

	public PhotoPagerTabAdapter(Fragment fragment, ViewPager viewPager) {
		super(fragment.getChildFragmentManager());
		this.mFManager = fragment.getChildFragmentManager();
		this.mContext = fragment.getActivity();
		viewPager.setAdapter(this);
		this.mViewPager = viewPager;
		
	}

	public static final class ItemInfo {
		private final int itemId;

		public int getItemId() {
			return itemId;
		}

		public String getTitle() {
			return title;
		}

		public Class<?> getClazz() {
			return clazz;
		}

		public Bundle getArgs() {
			return args;
		}

		private final String title;
		private final Class<?> clazz;
		private final Bundle args;
		/**
		 * 是否显示过
		 */
		private boolean isShowed = false;

		ItemInfo(int itemId, String title, Class<?> clazz, Bundle args) {
			this.itemId = itemId;
			this.title = title;
			this.clazz = clazz;
			this.args = args;
		}
	}

	public void addItemInfo(int itemId, String title, Class<?> clazz,
			Bundle args) {
		ItemInfo tabInfo = new ItemInfo(itemId, title, clazz, args);
		mItems.add(tabInfo);
		notifyDataSetChanged();
	}

	public void addItemInfo(int addToIndex, int itemId, String title,
			Class<?> clazz, Bundle args) {
		ItemInfo tabInfo = new ItemInfo(itemId, title, clazz, args);
		mItems.add(addToIndex, tabInfo);
		notifyDataSetChanged();
	}

	@Override
	public CharSequence getPageTitle(int position) {
		if (mItems.size() == 0) {
			return "";
		}
		return mItems.get(position % mItems.size()).title;
	}

	@Override
	public int getCount() {
		return mItems.size();
	}

	@Override
	public Fragment getItem(int position) {
		ItemInfo info = mItems.get(position);
		return Fragment.instantiate(mContext, info.clazz.getName(), info.args);
	}

	@Override
	public int getItemPosition(Object object) {
		return PagerAdapter.POSITION_NONE;
	}

	public void removeItem(int position) {
		Fragment fragment = (Fragment) instantiateItem(this.mViewPager,
				position);
		removeFragment(fragment);
		this.mItems.remove(position);
		notifyDataSetChanged();
	}

	public void removeAll() {
		FragmentTransaction ft = mFManager.beginTransaction();
		List<Fragment> fragments = mFManager.getFragments();
		for (Fragment fragment : fragments) {
			ft.remove(fragment);
		}
		ft.commitAllowingStateLoss();
		this.mItems.clear();
		notifyDataSetChanged();
	}

	private void removeFragment(Fragment fragment) {
		FragmentTransaction ft = mFManager.beginTransaction();
		ft.remove(fragment);
		ft.commitAllowingStateLoss();
	}

	@Override
	public long getItemId(int position) {
		ItemInfo tabInfo = this.mItems.get(position);
		return tabInfo.itemId;
	}

	public ItemInfo getItemInfo(int position) {
		return this.mItems.get(position);
	}

	/**
	 * 如果你需要在某个 Fragment 第一次显示的时候做一些事情（例如网络请求） ，那么，你需要在这个 Fragment 类中实现该接口。</br>
	 * If you need to do some things, when a Fragment show for the first time
	 * (such as network request) , so, you need to implement the interface in
	 * the Fragment class.
	 */
	public interface OnItemFirstShowListener {
		void onItemFirstShow();
	}

	@Override
	public void setPrimaryItem(ViewGroup container, int position, Object object) {
		Fragment fragment = (Fragment) object;
		if (fragment != mCurrentPrimaryItem) {
			if (fragment != null) {
				if (!fragment.isVisible()) {
					// 已创建，但当前未显示
					return;
				}
				ItemInfo tabInfo = this.mItems.get(position);
				if (tabInfo.isShowed) {
					// 不是第一次显示了
					return;
				}
				tabInfo.isShowed = true;
				OnItemFirstShowListener itemFirstLoadListener = null;
				try {
					if (fragment instanceof OnItemFirstShowListener){
						itemFirstLoadListener = (OnItemFirstShowListener) fragment;
					}
				} catch (ClassCastException e) {
					Log.i(TAG,
							"ViewPager Tip : If you need to do some things, "
									+ "when "
									+ fragment.getClass().getSimpleName()
									+ " view show for the first time (such as network request) , "
									+ "so, you need to implement the "
									+ OnItemFirstShowListener.class
											.getSimpleName()
									+ " interface in the "
									+ fragment.getClass().getSimpleName()
									+ " class.");
				}
				if (itemFirstLoadListener != null)
					itemFirstLoadListener.onItemFirstShow();
			}
			mCurrentPrimaryItem = fragment;
		}
		super.setPrimaryItem(container, position, object);
	}
}
